import queue
import time
import serial
import loggers

config_plc = ['01 05 00 01 00 00 9C 0A',    # 相机除尘关0
              '01 05 00 00 00 00 CD CA',    # 光源吹气关1
              '01 05 00 02 00 00 6C 0A',    # NG信号关2
              '01 05 00 03 00 00 3D CA',    # 光源关3
              '01 05 00 01 FF 00 DD FA',    # 相机除尘开4
              '01 05 00 00 FF 00 8C 3A',    # 光源吹气开5
              '01 05 00 02 FF 00 2D FA',    # NG信号开6
              '01 05 00 03 FF 00 7C 3A',    # 光源开7
              '01 02 00 00 00 08 79 CC',    # 输入测试8
              ]
class IOConnect:
    def __init__(self, io_connect_id, io_connect_bps, send_mode='hex'):
        self.send_mode = send_mode
        self.io_connect_id = io_connect_id
        self.io_connect_bps = io_connect_bps
        self.wait_time = 0
        self.qq = queue.Queue()
        a = 1
        while a:
            try:
                self.server_connect = serial.Serial(io_connect_id, io_connect_bps, timeout=0.1)
                a = 0
                loggers.log.info(f'IO板连接成功')
            except Exception as e:
                loggers.log.error(f'IO板连接失败:{e}')
                time.sleep(1)

    def write_str(self, datas,index):
        data = self.str2data(datas)
        self.server_connect.write(data)
    # if index == 8:
        msg_get = self.server_connect.readline()
        datas = self.data2str(msg_get)
        return datas
        # else:
        #     return 0
    def get_str(self):
        ret = self.qq.get()
        if ret is None:
            return ret

        datas = self.data2str(ret)
        return datas

    def data2str(self, data):
        if self.send_mode == 'hex':
            datas = ' '.join([f'{x:02x}' for x in data])
        else:
            datas = str(data, encoding='ASCII')
        return datas

    def str2data(self, datas):
        if self.send_mode == 'hex':
            data = bytes.fromhex(datas)  # value是str
        else:
            data = datas.encode('ASCII')  # value是str

        return data

    def plc_send(self, index):
        msg = config_plc[index]
        re_msg = self.write_str(msg,index)
        # loggers.log.info(f'plc数据发送成功{re_msg}')
        return re_msg
    
    def start_dianji(self):
        try:
            self.plc_send(4)
            time.sleep(1)
            self.plc_send(0)
            loggers.log.info(f'相机除灰成功')
        except Exception as e:
            loggers.log.error(f'相机除灰失败:{e}')
    def stop(self):
        self.server_connect.close()

    def check_safe(self):
        try:
            msg = self.plc_send()
            if msg is not None:
                self.qq.put(msg)
            time.sleep(0.1)
        except Exception as e:
            loggers.log.error(f'安全信号获取失败:{e}')
if __name__ == '__main__':
    plc = IOConnect('COM1', 38400)
    msg = plc.plc_send(8)
    print(time.time(),msg)
